package org.hikari.qqbot.client.message;

import lombok.*;

import java.util.HashMap;
import java.util.Map;

/**
 * created at 2024-12-09 23:04:15
 *
 * @author yinchao
 * @version 1.0
 **/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class MessageSegment {

    private String type;
    private Map<String, Object> data;

    public void dataValue(String key, Object value) {
        if (data == null) {
            this.data = new HashMap<>();
        }
        this.data.put(key, value);
    }

    public Object dataValue(String key) {
        return data == null ? null : data.get(key);
    }

    @SuppressWarnings("unchecked")
    public <T> T dataValueAs(String key) {
        return (T) dataValue(key);
    }

    public String dataValueToString(String key) {
        Object value = dataValue(key);
        if (value == null) {
            return null;
        }
        return value instanceof String ? (String) value : value.toString();
    }

    public Number dataValueToNumber(String key) {
        Object value = dataValue(key);
        return switch (value) {
            case null -> null;
            case Number number -> number;
            case String s -> s.contains(".") ? Double.parseDouble(s) : Long.parseLong(s);
            default ->
                    throw new NumberFormatException("Cannot convert value type '" + value.getClass().getName() + "' to a number");
        };
    }

    public Integer dataValueToInteger(String key) {
        Number value = dataValueToNumber(key);
        if (value == null) {
            return null;
        }
        return value.intValue();
    }

    public Long dataValueToLong(String key) {
        Number value = dataValueToNumber(key);
        if (value == null) {
            return null;
        }
        return value.longValue();
    }

    public Float dataValueToFloat(String key) {
        Number value = dataValueToNumber(key);
        if (value == null) {
            return null;
        }
        return value.floatValue();
    }

    public Double dataValueToDouble(String key) {
        Number value = dataValueToNumber(key);
        if (value == null) {
            return null;
        }
        return value.doubleValue();
    }

}
